/**
 * 思维导图可视化组件 - 基于 D3.js 重构
 * 
 * 技术栈说明：
 * - 核心引擎：D3.js (替代 Graphin，避免依赖问题)
 * - 布局算法：D3 树形布局，支持多种方向和自定义配置
 * - 交互功能：缩放、拖拽、节点展开/折叠、高亮等
 * - 响应式设计：支持不同设备尺寸自适应
 */

import React, { useRef, useEffect, useState, forwardRef, useImperativeHandle, useMemo } from 'react';
import { Button, Space, Tooltip, message, Select, Dropdown, Menu } from 'antd';
import {
  ZoomInOutlined,
  ZoomOutOutlined,
  ReloadOutlined,
  ExpandOutlined,
  CompressOutlined,
  FullscreenOutlined,
  DownloadOutlined,
  SettingOutlined,
  BgColorsOutlined,
  BranchesOutlined
} from '@ant-design/icons';
import * as d3 from 'd3';
import { transformDataForMindMap, generateMindMapColors, calculateMindMapLayout, generateMindMapPath } from '../../utils/mindMapUtils.jsx';

// 预设主题颜色方案
const COLOR_SCHEMES = {
  default: ['#52c41a', '#1677ff', '#fa8c16', '#722ed1', '#13c2c2', '#eb2f96', '#f5222d', '#faad14'],
  bright: ['#FF6B3B', '#626681', '#FFC100', '#9FB40F', '#76523B', '#DAD5B5', '#0E8E89', '#E19348'],
  colorful: ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14', '#F04864', '#8543E0', '#3436C7', '#223273'],
  vivid: ['#F5222D', '#FA8C16', '#FADB14', '#52C41A', '#13C2C2', '#1890FF', '#2F54EB', '#722ED1'],
  warm: ['#FF4500', '#FF8C00', '#FFD700', '#FFA07A', '#FF6347', '#FF7F50', '#FF69B4', '#FFB6C1'],
  cool: ['#00BFFF', '#00CED1', '#00FA9A', '#00FF7F', '#87CEFA', '#87CEEB', '#98FB98', '#AFEEEE']
};

// 预设背景样式
const BACKGROUNDS = {
  light: 'linear-gradient(135deg, #f6ffed 0%, #f0f9ff 100%)',
  dark: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)',
  blue: 'linear-gradient(135deg, #e6f7ff 0%, #e6fffb 100%)',
  green: 'linear-gradient(135deg, #f6ffed 0%, #fcffe6 100%)',
  warm: 'linear-gradient(135deg, #fff7e6 0%, #fff1f0 100%)',
  cool: 'linear-gradient(135deg, #f0f5ff 0%, #fcfcfc 100%)'
};

// 布局方向选项
const DIRECTIONS = {
  'H': '水平布局',
  'V': '垂直布局',
  'LR': '从左到右',
  'RL': '从右到左',
  'TB': '从上到下',
  'BT': '从下到上'
};

const MindMapVisualization = forwardRef(({ 
  nodes = [], 
  edges = [], 
  onNodeClick,
  onEdgeClick,
  editable = false,
  width = '100%',
  height = 500
}, ref) => {
  const svgRef = useRef(null);
  const containerRef = useRef(null);
  const [currentZoom, setCurrentZoom] = useState(1);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [colorScheme, setColorScheme] = useState('default');
  const [background, setBackground] = useState('light');
  const [direction, setDirection] = useState('H');
  const [expandedNodes, setExpandedNodes] = useState(new Set());
  const [selectedNode, setSelectedNode] = useState(null);

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    centerGraph: handleFitView,
    startSimulation: () => {}, // 思维导图不需要力导向动画
    pauseSimulation: () => {},
    updateAnimationSpeed: () => {},
    exportImage: handleExportImage,
    expandAll: handleExpandAll,
    collapseAll: handleCollapseAll,
    getGraph: () => ({ nodes, edges, type: 'mindmap' }),
    changeColorScheme: (scheme) => setColorScheme(scheme),
    changeBackground: (bg) => setBackground(bg),
    changeDirection: (dir) => setDirection(dir)
  }));

  // 获取当前颜色方案
  const getCurrentColors = () => {
    return COLOR_SCHEMES[colorScheme] || COLOR_SCHEMES.default;
  };

  // 获取当前背景
  const getCurrentBackground = () => {
    return BACKGROUNDS[background] || BACKGROUNDS.light;
  };

  // 渲染思维导图
  useEffect(() => {
    if (!svgRef.current || !nodes || nodes.length === 0) return;

    const svg = d3.select(svgRef.current);
    svg.selectAll('*').remove();

    const container = svg.append('g').attr('class', 'mindmap-container');
    
    const containerWidth = containerRef.current?.clientWidth || 800;
    const containerHeight = containerRef.current?.clientHeight || 500;

    // 创建缩放行为
    const zoomBehavior = d3.zoom()
      .scaleExtent([0.1, 4])
      .on('zoom', (event) => {
        const transform = event.transform;
        container.attr('transform', `translate(${transform.x}, ${transform.y}) scale(${transform.k})`);
        setCurrentZoom(transform.k);
      });

    svg.call(zoomBehavior);

    // 转换数据为思维导图格式
    const mindMapData = transformDataForMindMap(nodes, edges);
    const colors = getCurrentColors();

    // 创建层次布局
    const root = d3.hierarchy(mindMapData);
    
    let treeLayout;
    if (direction === 'H' || direction === 'LR' || direction === 'RL') {
      treeLayout = d3.tree()
        .size([containerHeight - 100, containerWidth - 200])
        .separation((a, b) => (a.parent === b.parent ? 1 : 2) / a.depth);
    } else {
      treeLayout = d3.tree()
        .size([containerWidth - 200, containerHeight - 100])
        .separation((a, b) => (a.parent === b.parent ? 1 : 2) / a.depth);
    }

    treeLayout(root);

    // 调整根节点位置到中心
    if (direction === 'H' || direction === 'LR' || direction === 'RL') {
      root.x = containerHeight / 2;
      root.y = 100;
    } else {
      root.x = containerWidth / 2;
      root.y = 100;
    }

    // 绘制连接线
    const linkGenerator = direction === 'H' || direction === 'LR' || direction === 'RL' 
      ? d3.linkHorizontal().x(d => d.y).y(d => d.x)
      : d3.linkVertical().x(d => d.x).y(d => d.y);

    const links = container.selectAll('.link')
      .data(root.links())
      .enter()
      .append('path')
      .attr('class', 'link')
      .attr('d', linkGenerator)
      .style('fill', 'none')
      .style('stroke', (d, i) => colors[d.target.depth % colors.length])
      .style('stroke-width', d => Math.max(2, 5 - d.target.depth))
      .style('opacity', 0.8);

    // 绘制节点
    const nodeGroups = container.selectAll('.node')
      .data(root.descendants())
      .enter()
      .append('g')
      .attr('class', 'node')
      .attr('transform', d => direction === 'H' || direction === 'LR' || direction === 'RL' 
        ? `translate(${d.y}, ${d.x})` 
        : `translate(${d.x}, ${d.y})`
      )
      .style('cursor', editable ? 'pointer' : 'default');

    // 节点背景
    nodeGroups.append('rect')
      .attr('width', d => Math.max(80, (d.data.name || '').length * 8 + 20))
      .attr('height', 30)
      .attr('x', d => -Math.max(40, (d.data.name || '').length * 4 + 10))
      .attr('y', -15)
      .attr('rx', 15)
      .style('fill', d => colors[d.depth % colors.length])
      .style('stroke', '#fff')
      .style('stroke-width', 2)
      .style('opacity', 0.9)
      .style('filter', 'drop-shadow(0 2px 4px rgba(0,0,0,0.2))');

    // 节点文本
    nodeGroups.append('text')
      .attr('dy', '0.35em')
      .attr('text-anchor', 'middle')
      .style('fill', '#fff')
      .style('font-size', d => Math.max(10, 14 - d.depth))
      .style('font-weight', d => d.depth === 0 ? 'bold' : 'normal')
      .text(d => {
        const name = d.data.name || '';
        return name.length > 10 ? name.substring(0, 10) + '...' : name;
      });

    // 添加展开/折叠按钮
    nodeGroups.filter(d => d.children || d._children)
      .append('circle')
      .attr('r', 8)
      .attr('cx', d => Math.max(40, (d.data.name || '').length * 4 + 10) + 15)
      .attr('cy', 0)
      .style('fill', '#fff')
      .style('stroke', d => colors[d.depth % colors.length])
      .style('stroke-width', 2)
      .style('cursor', 'pointer')
      .on('click', function(event, d) {
        event.stopPropagation();
        toggleNode(d);
      });

    nodeGroups.filter(d => d.children || d._children)
      .append('text')
      .attr('x', d => Math.max(40, (d.data.name || '').length * 4 + 10) + 15)
      .attr('y', 0)
      .attr('dy', '0.35em')
      .attr('text-anchor', 'middle')
      .style('fill', d => colors[d.depth % colors.length])
      .style('font-size', '10px')
      .style('font-weight', 'bold')
      .style('cursor', 'pointer')
      .text(d => d.children ? '-' : '+')
      .on('click', function(event, d) {
        event.stopPropagation();
        toggleNode(d);
      });

    // 节点点击事件
    if (onNodeClick) {
      nodeGroups.on('click', function(event, d) {
        setSelectedNode(d.data);
        onNodeClick(d.data);
      });
    }

    // 展开/折叠节点功能
    function toggleNode(d) {
      if (d.children) {
        d._children = d.children;
        d.children = null;
        setExpandedNodes(prev => {
          const newSet = new Set(prev);
          newSet.delete(d.data.id);
          return newSet;
        });
      } else {
        d.children = d._children;
        d._children = null;
        setExpandedNodes(prev => new Set(prev).add(d.data.id));
      }
      
      // 重新渲染
      renderMindMap();
    }

    function renderMindMap() {
      // 重新计算布局
      treeLayout(root);
      
      if (direction === 'H' || direction === 'LR' || direction === 'RL') {
        root.x = containerHeight / 2;
        root.y = 100;
      } else {
        root.x = containerWidth / 2;
        root.y = 100;
      }

      // 更新连接线
      const linkUpdate = container.selectAll('.link')
        .data(root.links());

      linkUpdate.exit().remove();

      linkUpdate.enter()
        .append('path')
        .attr('class', 'link')
        .merge(linkUpdate)
        .transition()
        .duration(500)
        .attr('d', linkGenerator);

      // 更新节点
      const nodeUpdate = container.selectAll('.node')
        .data(root.descendants());

      nodeUpdate.exit().remove();

      const nodeEnter = nodeUpdate.enter()
        .append('g')
        .attr('class', 'node');

      nodeEnter.merge(nodeUpdate)
        .transition()
        .duration(500)
        .attr('transform', d => direction === 'H' || direction === 'LR' || direction === 'RL' 
          ? `translate(${d.y}, ${d.x})` 
          : `translate(${d.x}, ${d.y})`
        );
    }

  }, [nodes, edges, expandedNodes, editable, onNodeClick, direction, colorScheme]);

  // 控制函数
  const handleZoomIn = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity.scale(currentZoom * 1.2)
    );
    setCurrentZoom(prev => prev * 1.2);
  };

  const handleZoomOut = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity.scale(currentZoom / 1.2)
    );
    setCurrentZoom(prev => prev / 1.2);
  };

  const handleFitView = () => {
    const svg = d3.select(svgRef.current);
    const containerWidth = containerRef.current?.clientWidth || 800;
    const containerHeight = containerRef.current?.clientHeight || 500;
    
    svg.transition()
      .duration(750)
      .call(
        d3.zoom().transform,
        d3.zoomIdentity
          .translate(containerWidth / 2, containerHeight / 2)
          .scale(1)
      );
    setCurrentZoom(1);
  };

  const handleExpandAll = () => {
    setExpandedNodes(new Set(nodes.map(n => n.id)));
    message.success('已展开所有节点');
  };

  const handleCollapseAll = () => {
    setExpandedNodes(new Set());
    message.success('已折叠所有分支');
  };

  const handleExportImage = () => {
    if (!svgRef.current) return;
    
    try {
      const svg = svgRef.current;
      const serializer = new XMLSerializer();
      const source = serializer.serializeToString(svg);
      
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      const img = new Image();
      
      img.onload = () => {
        canvas.width = img.width;
        canvas.height = img.height;
        context.drawImage(img, 0, 0);
        
        const link = document.createElement('a');
        link.download = '思维导图.png';
        link.href = canvas.toDataURL();
        link.click();
      };
      
      img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(source)));
      message.success('图片导出成功');
    } catch (error) {
      console.error('导出图片失败:', error);
      message.error('图片导出失败，请稍后重试');
    }
  };

  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  // 颜色方案菜单
  const colorSchemeMenu = (
    <Menu
      onClick={({ key }) => setColorScheme(key)}
      selectedKeys={[colorScheme]}
    >
      <Menu.Item key="default">默认配色</Menu.Item>
      <Menu.Item key="bright">明亮配色</Menu.Item>
      <Menu.Item key="colorful">多彩配色</Menu.Item>
      <Menu.Item key="vivid">鲜艳配色</Menu.Item>
      <Menu.Item key="warm">暖色调</Menu.Item>
      <Menu.Item key="cool">冷色调</Menu.Item>
    </Menu>
  );

  // 布局方向菜单
  const directionMenu = (
    <Menu
      onClick={({ key }) => setDirection(key)}
      selectedKeys={[direction]}
    >
      {Object.entries(DIRECTIONS).map(([key, label]) => (
        <Menu.Item key={key}>{label}</Menu.Item>
      ))}
    </Menu>
  );

  return (
    <div 
      ref={containerRef}
      style={{ 
        position: isFullscreen ? 'fixed' : 'relative',
        top: isFullscreen ? 0 : 'auto',
        left: isFullscreen ? 0 : 'auto',
        width: isFullscreen ? '100vw' : width,
        height: isFullscreen ? '100vh' : height,
        zIndex: isFullscreen ? 9999 : 'auto',
        border: '1px solid #d9d9d9', 
        borderRadius: isFullscreen ? 0 : '8px',
        overflow: 'hidden', 
        background: getCurrentBackground()
      }}
    >
      {/* 工具栏 */}
      <div style={{
        position: 'absolute',
        top: '8px',
        right: '8px',
        zIndex: 10,
        background: 'rgba(255, 255, 255, 0.95)',
        borderRadius: '6px',
        padding: '8px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <Space size="small">
          <Tooltip title="展开全部">
            <Button size="small" icon={<ExpandOutlined />} onClick={handleExpandAll} />
          </Tooltip>
          <Tooltip title="折叠全部">
            <Button size="small" icon={<CompressOutlined />} onClick={handleCollapseAll} />
          </Tooltip>
          <Tooltip title="放大">
            <Button size="small" icon={<ZoomInOutlined />} onClick={handleZoomIn} />
          </Tooltip>
          <Tooltip title="缩小">
            <Button size="small" icon={<ZoomOutOutlined />} onClick={handleZoomOut} />
          </Tooltip>
          <Tooltip title="适应画布">
            <Button size="small" icon={<ReloadOutlined />} onClick={handleFitView} />
          </Tooltip>
          <Tooltip title="导出图片">
            <Button size="small" icon={<DownloadOutlined />} onClick={handleExportImage} />
          </Tooltip>
          <Tooltip title={isFullscreen ? "退出全屏" : "全屏显示"}>
            <Button size="small" icon={<FullscreenOutlined />} onClick={toggleFullscreen} />
          </Tooltip>
          <Dropdown overlay={colorSchemeMenu} placement="bottomRight">
            <Button size="small" icon={<BgColorsOutlined />} />
          </Dropdown>
          <Dropdown overlay={directionMenu} placement="bottomRight">
            <Button size="small" icon={<BranchesOutlined />} />
          </Dropdown>
        </Space>
      </div>

      {/* SVG 画布 */}
      <div style={{ width: '100%', height: '100%' }}>
        <svg
          ref={svgRef}
          width="100%"
          height="100%"
          style={{ display: 'block' }}
        />
      </div>

      {/* 状态指示器 */}
      <div style={{
        position: 'absolute',
        bottom: '8px',
        left: '8px',
        background: 'rgba(0,0,0,0.7)',
        color: 'white',
        padding: '4px 8px',
        borderRadius: '4px',
        fontSize: '12px'
      }}>
        <Space size="small">
          <span>思维导图 (D3.js)</span>
          <span>|</span>
          <span>缩放: {Math.round(currentZoom * 100)}%</span>
          <span>|</span>
          <span>节点: {nodes.length}</span>
          <span>|</span>
          <span>方向: {DIRECTIONS[direction]}</span>
        </Space>
      </div>
      
      {/* 使用说明 */}
      {nodes.length === 0 && (
        <div style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          textAlign: 'center',
          color: '#999'
        }}>
          <p>暂无数据</p>
          <p style={{ fontSize: '12px' }}>请添加节点和关系来构建思维导图</p>
        </div>
      )}
    </div>
  );
});

MindMapVisualization.displayName = 'MindMapVisualization';

export default MindMapVisualization;